import { Body, Controller, Get, Param, Post, Req, UsePipes, ValidationPipe } from '@nestjs/common';
import exceptionFactory from 'src/pip/exceptionFactory';
import { errorReturn, successReturn } from 'src/util';
import { ChargeService } from './charge.service';
import AddChargeDto from './dto/AddCharge.dto';
import ChargeDto from './dto/Charge.dto';

@Controller('charge')
export class ChargeController {
    constructor(
        private chargeService:ChargeService
    ){}
    @Post()
    @UsePipes(new ValidationPipe({stopAtFirstError : true, whitelist : true, transform : true, exceptionFactory : exceptionFactory}))
    async chage(@Body() chargeDto:ChargeDto, @Req() { userId, clientSource }) {
        try {
            const orderId = await this.chargeService.charge(chargeDto, userId, clientSource)
            if(orderId != false) return successReturn(orderId)
        } catch (error) {
            console.error(error.message)
        }

        return errorReturn()
    }

    //查询充电是否成功
    @Get('status/:orderId')
    async chargeOrderStatus(@Param('orderId') orderId:number) {
        let status = await this.chargeService.queryChargeOrderStatus(orderId) //0等待结果，1：成功，2：失败
        return status === undefined ? errorReturn() : successReturn(status)
    }

    //增加充电
    @Post('addCharge')
    @UsePipes(new ValidationPipe({stopAtFirstError : true, whitelist : true, transform : true, exceptionFactory : exceptionFactory}))
    async addCharge(@Body() addChargeDto:AddChargeDto, @Req() { userId }) {
        try {
            let orderId = await this.chargeService.addCharge(addChargeDto.orderId, addChargeDto.amount, userId)
            if(orderId != false) return successReturn(orderId)
        } catch (error) {
            console.error(error.message)
        }
        return errorReturn()
    }

    //查询增加充电是否成功
    @Get('addStatus/:orderId')
    async addChargeOrderStatus(@Param('orderId') orderId:number) {
        let status = await this.chargeService.queryAddChargeOrderStatus(orderId) //0等待结果，1：成功，2：失败
        return status === undefined ? errorReturn() : successReturn(status)
    }

    //停止充电
    @Post('stop')
    async stopChargeOrder(@Body('orderId') orderId:number, @Req() { userId }) {
        if(isNaN(orderId) || orderId <= 0 ) return successReturn()
        let res = await this.chargeService.stopCharge(orderId, userId) //0等待结果，1：成功，2：失败
        return res ? successReturn() : errorReturn()
    }

    //查询停止充电是否成功
    @Get('stopStatus/:orderId')
    async stopChargeOrderStatus(@Param('orderId') orderId:number) {
        orderId = Number(orderId)
        if(isNaN(orderId) || orderId <= 0 ) return successReturn()
        let status = await this.chargeService.queryStopChargeOrderStatus(orderId) //0等待结果，1：成功，2：失败
        return status === undefined ? errorReturn() : successReturn(status)
    }
}
